package com.itrui.encrypted_transmission.Thread;

import com.itrui.encrypted_transmission.*;
import lombok.SneakyThrows;

import java.io.*;
import java.net.Socket;

public class MyServerThread implements Runnable{

    private Socket socket;

    public MyServerThread(Socket socket) {
        this.socket = socket;
    }



    @SneakyThrows
    @Override
    public void run() {
        String mFilePath = "D:\\RuiProject\\FileTest";
        File dirs = new File(mFilePath);
        if (!dirs.exists()) {
            dirs.mkdirs();
        }

        //通过socket.getInputStream() 读取客户端写入到数据通道的数据
        BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
        DataInputStream dis = new DataInputStream(socket.getInputStream());
        String privateKeyHex = dis.readUTF();
        System.out.println("-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-");
        System.out.println("私钥是：" + privateKeyHex);

       /* int num = dis.readInt();
        System.out.println("文件数：" + num);*/


        //获取原始加密字符串
        String s = StreamUtils.streamToString(bis);
        //解密
        String decrypt = SM2Utils.decrypt(privateKeyHex, s);
        //反序列化
        MyFile myFile = JOSNUtils.deserialize(decrypt);
        //保存到文件夹中
        System.out.println("正在保存"+myFile.getName()+"...");
        CodeUtils.loadFile(myFile.getFile(), "D:\\RuiProject\\Server\\" + myFile.getName());


        System.out.println(myFile.getName()+"已被成功接收！");
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        bw.write(myFile.getName()+"接收完成！");
        bw.newLine();
        bw.flush();

        bis.close();
        socket.close();
    }
}
